package com.the_ring.chapter09;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.RadioGroup;


import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.widget.ViewPager2;

import com.the_ring.chapter09.adapter.MainAdapter;
import com.the_ring.chapter09.fragment.CartFragment;
import com.the_ring.chapter09.fragment.ClassifyFragment;
import com.the_ring.chapter09.fragment.FirstFragment;

import java.util.ArrayList;
import java.util.List;

public class MallMainActivity extends AppCompatActivity implements RadioGroup.OnCheckedChangeListener {

    private static final String TAG = "MallMainActivity";

    private ViewPager2 mainViewPager;
    private RadioGroup bottomRg;

    private List<Fragment> fragments;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mall_main);

        mainViewPager = findViewById(R.id.vp_main);
        fragments = new ArrayList<>();
        fragments.add(FirstFragment.newInstance(this));
        fragments.add(ClassifyFragment.newInstance(this));
        fragments.add(CartFragment.newInstance());
        mainViewPager.setAdapter(new MainAdapter(getSupportFragmentManager(), getLifecycle(), fragments));
        mainViewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                super.onPageScrolled(position, positionOffset, positionOffsetPixels);
                Log.i(TAG, "onPageScrolled " + position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                super.onPageScrollStateChanged(state);
                Log.i(TAG, "onPageScrollStateChanged " + state);
            }

            @Override
            public void onPageSelected(int position) {
                // 滑动底部选中
                bottomRg.check(bottomRg.getChildAt(position).getId());
            }
        });
        mainViewPager.setCurrentItem(0);

        bottomRg = findViewById(R.id.rg_main);
        bottomRg.setOnCheckedChangeListener(this);
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        // 选中底部跳转到指定页
        if (checkedId == R.id.rb_first) {
            mainViewPager.setCurrentItem(0, true);
        } else if (checkedId == R.id.rb_classify) {
            mainViewPager.setCurrentItem(1, true);
        } else if (checkedId == R.id.rb_cart) {
            mainViewPager.setCurrentItem(2, true);
        }
    }
}